<template>
  <Container class="role-edit">
    <div class="container-header title title-center" slot="header">
      {{ title }}
      <Button size="large" class="fl btn-back" icon="ios-arrow-back" @click="jumpPrevPage">返回</Button>
    </div>
    <div class="bgs">
      <Form :label-width="80" class="form" :model="form" ref="form" :rules="rules">
        <FormItem label="政策名称" prop="name">
          <Input
            :maxlength="20"
            class="common-width"
            v-model.trim="form.name"
            placeholder="请输入2-20位字符的政策名称"
          />
        </FormItem>
        <FormItem label="生效时间" prop="date">
          <DatePicker
            v-model="form.date"
            type="daterange"
            placeholder="请选择生效时间"
            class="common-width"
          ></DatePicker>
        </FormItem>
      </Form>
      <div class="table-content">
        <Table border :columns="list.columns" :data="list.data"></Table>
      </div>
    </div>

    <Loader :status="status" @refresh="getInfo"></Loader>
    <div class="container-footer bg-white" slot="footer">
      <div>
        <Button type="primary" class="mr" size="large" @click="onSave">保存</Button>
        <Button type="primary" class="mr" size="large" @click="cancle">取消</Button>
      </div>
    </div>
  </Container>
</template>
<script>
import table from "@/table";
// import data from "./edit/PolicyLimitsEditItemData";
import { formatDate, getOriginData } from "@/util";
// import { Input ,InputNumber } from "view-design";
import { mapGetters } from "vuex";

export default {
  data() {
    const validateName = (rule, value, callback) => {
      if (value.trim() === "") {
        callback(new Error("请输入政策名称"));
      } else {
        if (value.length < 2) {
          callback(new Error("政策名称在2-20个字之间"));
        }
        callback();
      }
    };
    const validateDate = (rule, value, callback) => {
      if (value[0] === "") {
        callback(new Error("请必须输入时间"));
      }
      callback();
    };
    return {
      id: this.$route.query.id || "",
      title: "",
      status: "pass",
      isDisabled: false,
      inputModel: [],
      form: {
        name: "",
        date: [],
      },
      rules: {
        name: [{ required: true, validator: validateName, trigger: "blur" }],
        date: [{ required: true, validator: validateDate, trigger: "blur" }],
      },
      options: {
        tableHeight: 300,
      },
      storeType: [],
      list: {
        data: [],
        brandList: [],
        columns: [],
        tableInfoList: [],
        columns: [
          {
            title: "门店类型",
            key: "storeTypeName",
            align: 'left',
          },
          {
            title: "品牌",
            key: "brandName",
            align: 'left',
            render: (h, params) => {
              return this.list.brandList.map((e) => {
                return h( "p",
                  {
                    style: {
                      padding: "9px",
                    },
                  },
                  [h("strong", e.brandName)]
                );
              });
            },
          },
          {
            title: "最低签约条数",
            key: "taskQuantity",
            align: 'left',
            render: (h, p) => {
              return this.list.brandList.map((s, i) => {
                return h("InputNumber", {
                  props: {
                    min: 0,
                    max: 99999,
                    value: p.row.brandList[i].taskQuantity || 0,
                  },
                  style: {
                    display: "block",
                    margin: "5px auto",
                  },
                  on: {
                    "on-change": (e) => {
                      p.row.brandList[i].taskQuantity = e;
                      this.$set(
                        this.list.data[p.index].brandList[i],
                        "taskQuantity",
                        e
                      );
                    },
                  },
                });
              });
            },
          },
          {
            title: "最高计算积分返利量",
            key: "maxIntegralQuantity",
            align: 'left',
            render: (h, p) => {
              return h("InputNumber", {
                props: {
                  min: 0,
                  max: 99999,
                  value: p.row.maxIntegralQuantity,
                },
                on: {
                  "on-change": (e) => {
                    p.row.maxIntegralQuantity = e;
                    this.$set(this.list.data, p.index, p.row);
                  },
                },
              });
            },
          },
        ],
        policyItemsData: [],
      },
    };
  },
  mounted() {
    this.initTable(15);
    this.$refs.form.resetFields();
    if (this.$route.query.id) {
      this.id = this.$route.query.id;
      this.title = "编辑政策";
    } else {
      this.list.tableInfoList = [];
      this.title = "新增政策";
    }
    this.initData();
  },
  destroyed() {
    this.$bus.$off();
  },
  methods: {
    ...table,
    async initData() {
      this.list.data = [];
      await this.getBrandList();
      await this.getStoreList();
      await this.getInfo();
    },
    getBrandList() {
      return this.$ajaxGet("/product/common/supplier_brand").then((data) => {
        this.list.brandList = data.map((item) => {
          return {
            brandId: item.brandId,
            brandName: item.brandName,
          };
        });
      });
    },
    getStoreList() {
      this.status = "loading";
      return this.$ajaxGet("storeType/findAll").then((data) => {
        this.list.data = data.map((item) => {
          let obj = {
            storeTypeId: item.id,
            storeTypeName: item.name,
            taskQuantity: 0,
            maxIntegralQuantity: 0,
          };
          obj.brandList = getOriginData(this.list.brandList);
          return obj;
        });
        this.status = "pass";
      });
    },
    getInfo() {
      if (!this.id) return;
      this.status = "loading";
      return this.$ajaxGet(
        `/setting/purchase_quantity_policy/detail/${this.id}`
      )
        .then((res) => {
          const {
            beginDate,
            createDate,
            endDate,
            policyName,
            policyItems,
          } = res;
          this.form.name = policyName;
          this.form.date = [formatDate(beginDate), formatDate(endDate)];
          let newArr = [];
          policyItems.forEach((item, i) => {
            let prev = newArr.find((e) => e.storeTypeId == item.storeTypeId);
            if (!prev) {
              let obj = {};
              obj.maxIntegralQuantity = item.maxIntegralQuantity;
              obj.storeTypeName = item.storeTypeName;
              obj.storeTypeId = item.storeTypeId;
              obj.brandList = [
                {
                  brandId: item.brandId,
                  brandName: item.brandName,
                  taskQuantity: item.taskQuantity,
                },
              ];
              newArr.push(obj);
            } else {
              prev.brandList = [
                ...prev.brandList,
                {
                  brandId: item.brandId,
                  brandName: item.brandName,
                  taskQuantity: item.taskQuantity,
                },
              ];
            }
          });
          this.list.data = newArr.map((item) => {
            let {
              maxIntegralQuantity,
              storeTypeId,
              storeTypeName,
              brandList,
            } = item;
            return {
              maxIntegralQuantity,
              storeTypeId,
              brandList,
              storeTypeName,
            };
            return item;
          });
          this.status = "pass";
        })
        .catch((err) => {
          this.status = "error";
        });
    },
    getParamList() {
      let arr = [];
      this.list.data.forEach((item, index) => {
        let val = item.brandList.map((e) => {
          return {
            maxIntegralQuantity: item.maxIntegralQuantity,
            taskQuantity: e.taskQuantity || 0,
            storeTypeId: item.storeTypeId,
            brandId: e.brandId,
            brandName: e.brandName,
            storeTypeName: item.storeTypeName,
          };
        });
        arr = arr.concat(val);
      });

      return arr;
    },
    onSave() {
      if (this.isDisabled) return;
      this.$refs["form"].validate((valid) => {
        if (valid) {
          let arr = this.getParamList();
          this.isDisabled = true;
          let url = this.id
            ? "/setting/purchase_quantity_policy/modify"
            : "/setting/purchase_quantity_policy/save";
          let text = this.id ? "编辑" : "新增";
          let param = {
            policyName: this.form.name || "",
            id: this.id,
            purchaseQuantityPolicyItems: arr || [],
          };
          if (this.form.date[0])
            param.beginDate = formatDate(this.form.date[0]) + " 00:00:00";
          if (this.form.date[1])
            param.endDate = formatDate(this.form.date[1]) + " 23:59:59";
          this.$jsonPost(url, param)
            .then((data) => {
              this.$Notice.success({
                title: `${text}成功`,
              });
              this.$router.push("/policy/policyLimits/list");
            })
            .catch(() => {
              this.isDisabled = false;
            });
        }
      });
    },
    cancle() {
      this.$router.back();
    },
    jumpPrevPage() {
      this.$router.back();
    },
  },
};
</script>